package com.yc.service.impl;

import com.yc.entity.Detail;
import com.yc.entity.Wallet;
import com.yc.mapper.DetailMapper;
import com.yc.mapper.WalletMapper;
import com.yc.service.WalletService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet> implements WalletService {

    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private DetailMapper detailMapper;
    @Override
    @Transactional
    public int spend(Wallet wallet, Double money) {
        int update = 0;
        int insert = 0;
        try {
            //计算新价格
            BigDecimal decimal = new BigDecimal(money);
            BigDecimal newMoney = wallet.getWalletBalance().subtract(decimal);
            wallet.setWalletBalance(newMoney);
            //修改钱包数据
            update = walletMapper.updateById(wallet);
            //添加钱包详情数据
            Detail detail = new Detail();
            detail.setDetailOperation(3);
            detail.setDetailMoney(decimal);
            detail.setWallet(wallet);
            detail.setDetailDate(LocalDateTime.now());
            insert = detailMapper.insertDetail(detail);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("余额不足");
        }
        return update&insert;
    }

    @Override
    @Transactional
    public int refund(Wallet wallet, Double money) {
        //修改钱包
        BigDecimal decimal = new BigDecimal(money);
        BigDecimal newMoney = wallet.getWalletBalance().add(decimal);
        wallet.setWalletBalance(newMoney);
        int update = walletMapper.updateById(wallet);
        //修改钱包详情
        Detail detail = new Detail();
        detail.setDetailOperation(2);
        detail.setDetailMoney(decimal);
        detail.setWallet(wallet);
        detail.setDetailDate(LocalDateTime.now());
        int insert = detailMapper.insertDetail(detail);
        return update&insert;
    }
}
